#include "EpilLocalVariableStatementParser.h"
#include "EpilParserException.h"
#include "EpilExpressionListParser.h"
#include "EpilPointerHelper.h"


EpilLocalVariableStatementParser::EpilLocalVariableStatementParser( EpilTokenStream & tokens )
: EpilSyntaxParserBase( tokens )
{
}


void EpilLocalVariableStatementParser::Parse()
{
	// stat -> LOCAL NAME {`,' NAME} [`=' explist1]
	m_statement = new EpilLocalVariableStatementCode( this->GetTokens().GetPreviousToken().location );

	for(;;)
	{
		if( this->GetTokens().GetCurrentToken().type != ETT_Identifier )
		{
			EpilPointerHelper::SafeDelete( m_statement );
			throw EpilParserException( t("Identifier expected."), this->GetTokens().GetCurrentToken().location );
		}
		m_statement->GetVariables().push_back( this->GetTokens().GetCurrentToken().text );
		this->GetTokens().MoveToNext();

		if( this->GetTokens().GetCurrentToken().type != ETT_OpComma )
		{
			break;
		}
		this->GetTokens().MoveToNext();
	}

	if( this->GetTokens().GetCurrentToken().type != ETT_OpAssign )
	{
		return;
	}
	this->GetTokens().MoveToNext();

	EpilExpressionListParser exprListParser( this->GetTokens() );
	try
	{
		exprListParser.Parse();
	}
	catch( ... )
	{
		EpilPointerHelper::SafeDelete( m_statement );
		throw;
	}
	m_statement->SetAssigners( exprListParser.GetExpressions() );
}